package io.polly.ldz.reactor.security;

import io.polly.ldz.reactor.context.SystemCode;
import io.polly.ldz.reactor.service.UserService;
import io.polly.ldz.reactor.util.JwtTokenUtil;
import io.polly.ldz.reactor.viewmodel.TokenVM;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @version 3.5.0
 * @description: 登录成功返回
 * Copyright (C), 2020-2021,
 * @date 2021/12/25 9:45
 */
@Component
public class RestAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {


    private final ApplicationEventPublisher eventPublisher;
    private final UserService userService;

    private final JwtTokenUtil jwtTokenUtil;

    /**
     * Instantiates a new Rest authentication success handler.
     *
     * @param eventPublisher the event publisher
     * @param userService    the user service
     */
    @Autowired
    public RestAuthenticationSuccessHandler(ApplicationEventPublisher eventPublisher, UserService userService,JwtTokenUtil jwtTokenUtil) {
        this.eventPublisher = eventPublisher;
        this.userService = userService;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Object object = authentication.getPrincipal();
        if (null != object) {
            User springUser = (User) object;
            io.polly.ldz.reactor.entity.User user = userService.getUserByUserName(springUser.getUsername());
            if (null != user) {

                TokenVM tokenVM = new TokenVM();
                tokenVM.setUserID(user.getId());
                tokenVM.setUserName(user.getUserName());
                tokenVM.setAccessToken(jwtTokenUtil.generateToken(user));

                RestUtil.response(response, SystemCode.OK.getCode(), SystemCode.OK.getMessage(), tokenVM);
            }
        } else {
            RestUtil.response(response, SystemCode.UNAUTHORIZED.getCode(), SystemCode.UNAUTHORIZED.getMessage());
        }
    }
}
